 <template>
  <div class="product-management">
    <div class="page-header">
      <h1>商品管理</h1>
      <p>管理系统中的所有商品信息</p>
    </div>

    <div class="content-card">
      <div class="toolbar">
        <div class="search-section">
          <input 
            type="text" 
            v-model="searchKeyword" 
            placeholder="输入商品编号或名称搜索"
            class="search-input"
          >
          <button class="btn btn-search" @click="searchProducts">搜索</button>
        </div>
        <button class="btn btn-primary" @click="showAddModal">新增商品</button>
      </div>

      <div class="table-container">
        <table class="product-table">
          <thead>
            <tr>
              <th>商品ID</th>
              <th>商品图片</th>
              <th>商品名称</th>
              <th>分类</th>
              <th>价格</th>
              <th>库存</th>
              <th>状态</th>
              <th>热销</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="product in products" :key="product.productId">
              <td>{{ product.productId }}</td>
              <td>
                <img 
                  :src="getValidImgUrl(product.productImg)"
                  :alt="product.productName"
                  class="product-img"
                  @error="handleImageError"
                >
              </td>
              <td>{{ product.productName }}</td>
              <td>
                <span v-if="product.categoryName" class="category-name">
                  {{ product.categoryName }}
                </span>
                <span v-else class="no-category">
                  <i class="no-category-icon">⚠️</i>
                  未分类
                </span>
              </td>
              <td>¥{{ product.sellingPrice }}</td>
              <td>{{ product.stock }}</td>
              <td>
                <label class="switch">
                  <input 
                    type="checkbox" 
                    :checked="product.status === 1"
                    @change="toggleProductStatus(product)"
                  >
                  <span class="slider"></span>
                </label>
              </td>
              <td>
                <label class="switch">
                  <input 
                    type="checkbox" 
                    :checked="product.isHot === 1"
                    @change="toggleHotStatus(product)"
                  >
                  <span class="slider"></span>
                </label>
              </td>
              <td>
                <button class="btn btn-edit" @click="editProduct(product)">编辑</button>
                <button class="btn btn-delete" @click="deleteProduct(product)">删除</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 新增/编辑商品模态框 -->
    <div v-if="showModal" class="modal-overlay" @click="closeModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>{{ isEditing ? '编辑商品' : '新增商品' }}</h3>
          <button class="close-btn" @click="closeModal">&times;</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="saveProduct">
            <div class="form-row">
              <div class="form-group">
                <label>商品名称 *</label>
                <input type="text" v-model="editingProduct.productName" required>
              </div>
              <div class="form-group">
                <label>商品分类</label>
                <select v-model="editingProduct.categoryId">
                  <option value="">请选择分类</option>
                  <option v-for="category in categories" :key="category.categoryId" :value="String(category.categoryId)">
                    {{ category.categoryName }}
                  </option>
                </select>
                <small v-if="categories.length === 0" class="form-help">
                  <i class="help-icon">⚠️</i>
                  暂无分类数据，请先添加分类
                </small>
              </div>
            </div>
            <div class="form-row">
              <div class="form-group">
                <label>销售价格 *</label>
                <input type="number" v-model="editingProduct.sellingPrice" step="0.01" min="0" required>
              </div>
              <div class="form-group">
                <label>库存数量 *</label>
                <input type="number" v-model="editingProduct.stock" min="0" required>
              </div>
            </div>
            <div class="form-group">
              <label>原价</label>
              <input type="number" v-model="editingProduct.originalPrice" step="0.01" min="0" required placeholder="请输入原价" />
            </div>
            <div class="form-group">
              <label>商品描述</label>
              <textarea v-model="editingProduct.productDesc" rows="3"></textarea>
            </div>
            <div class="form-group">
              <label>商品图片URL</label>
              <input type="url" v-model="editingProduct.productImg" placeholder="https://example.com/image.jpg">
            </div>
            <div class="form-row">
              <div class="form-group">
                <label>商品状态</label>
                <select v-model="editingProduct.status">
                  <option value="1">上架</option>
                  <option value="0">下架</option>
                </select>
              </div>
              <div class="form-group">
                <label>热销状态</label>
                <select v-model="editingProduct.isHot">
                  <option value="0">普通</option>
                  <option value="1">热销</option>
                </select>
              </div>
            </div>
            <div class="form-actions">
              <button type="button" class="btn btn-secondary" @click="closeModal">取消</button>
              <button type="submit" class="btn btn-primary">{{ isEditing ? '保存' : '新增' }}</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getAllProducts, addProduct, updateProduct, deleteProduct, searchProducts, getAllCategories, toggleProductStatus, toggleHotStatus } from '@/api/admin';

export default {
  name: 'ProductManagement',
  data() {
    return {
      products: [],
      categories: [],
      searchKeyword: '',
      showModal: false,
      isEditing: false,
      editingProduct: {
        productName: '',
        categoryId: '',
        sellingPrice: '',
        stock: '',
        productDesc: '',
        productImg: '',
        status: 1,
        isHot: 0
      },
      loading: false
    }
  },
  mounted() {
    this.fetchProducts();
    this.fetchCategories();
  },
  methods: {
    async fetchProducts() {
      try {
        this.loading = true;
        const response = await getAllProducts();
        this.products = response || [];
      } catch (error) {
        console.error('获取商品列表失败:', error);
        alert('获取商品列表失败');
      } finally {
        this.loading = false;
      }
    },
    async fetchCategories() {
      try {
        const response = await getAllCategories();
        this.categories = response || [];
        console.log('获取到的分类数据:', this.categories);
      } catch (error) {
        console.error('获取分类列表失败:', error);
        alert('获取分类列表失败，请检查分类数据');
      }
    },
    async searchProducts() {
      if (!this.searchKeyword.trim()) {
        this.fetchProducts();
        return;
      }
      
      try {
        const response = await searchProducts({ keyword: this.searchKeyword });
        this.products = response || [];
      } catch (error) {
        console.error('搜索商品失败:', error);
        alert('搜索商品失败');
      }
    },
    showAddModal() {
      this.isEditing = false;
      this.editingProduct = {
        productName: '',
        categoryId: '',
        sellingPrice: '',
        stock: '',
        productDesc: '',
        productImg: '',
        status: 1,
        isHot: 0
      };
      this.showModal = true;
    },
    editProduct(product) {
      this.isEditing = true;
      this.editingProduct = { ...product };
      this.showModal = true;
    },
    async saveProduct() {
      try {
        let response;
        if (this.isEditing) {
          response = await updateProduct(this.editingProduct);
        } else {
          response = await addProduct(this.editingProduct);
        }
        
        if ((response && response.status === 200) || (response && response.msg && response.msg.includes('成功'))) {
          alert(this.isEditing ? '商品修改成功' : '商品添加成功');
          this.closeModal();
          this.fetchProducts();
        } else {
          alert('操作失败');
        }
      } catch (error) {
        console.error('保存商品失败:', error);
        alert('保存商品失败');
      }
    },
    async deleteProduct(product) {
      if (!confirm(`确定要删除商品 "${product.productName}" 吗？`)) {
        return;
      }
      
      try {
        const response = await deleteProduct(product.productId);
        if ((response && response.status === 200) || (response && response.msg && response.msg.includes('成功'))) {
          alert('商品删除成功');
          this.fetchProducts();
        } else {
          alert('删除失败');
        }
      } catch (error) {
        console.error('删除商品失败:', error);
        alert('删除商品失败');
      }
    },
    async toggleProductStatus(product) {
      try {
        const newStatus = product.status === 1 ? 0 : 1;
        const response = await toggleProductStatus(product.productId, newStatus);
        if (response.status === 200) {
          product.status = newStatus;
          alert('商品状态修改成功');
        } else {
          alert(response.msg || '状态修改失败');
        }
      } catch (error) {
        console.error('修改商品状态失败:', error);
        alert('修改商品状态失败');
      }
    },
    async toggleHotStatus(product) {
      try {
        const newHotStatus = product.isHot === 1 ? 0 : 1;
        const response = await toggleHotStatus(product.productId, newHotStatus);
        if (response.status === 200) {
          product.isHot = newHotStatus;
          alert('热销状态修改成功');
        } else {
          alert(response.msg || '热销状态修改失败');
        }
      } catch (error) {
        console.error('修改热销状态失败:', error);
        alert('修改热销状态失败');
      }
    },
    closeModal() {
      this.showModal = false;
      this.editingProduct = {};
    },
    getValidImgUrl(url) {
      if (!url || url === '/admin/2' || url === '' || url === null || url === '2') {
        return '/product-default.png';
      }
      return url;
    },
    handleImageError(event) {
      event.target.src = '/product-default.png';
    }
  }
}
</script>

<style scoped>
.product-management {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 30px;
}

.page-header h1 {
  margin: 0 0 10px 0;
  color: #2c3e50;
  font-size: 2rem;
}

.page-header p {
  margin: 0;
  color: #7f8c8d;
}

.content-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  overflow: hidden;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #ecf0f1;
}

.search-section {
  display: flex;
  gap: 10px;
}

.search-input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  width: 300px;
}

.table-container {
  overflow-x: auto;
}

.product-table {
  width: 100%;
  border-collapse: collapse;
}

.product-table th,
.product-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ecf0f1;
}

.product-table th {
  background-color: #f8f9fa;
  font-weight: 600;
  color: #2c3e50;
}

.product-table tr:hover {
  background-color: #f8f9fa;
}

.product-img {
  width: 50px;
  height: 50px;
  object-fit: cover;
  border-radius: 4px;
}

.category-name {
  display: inline-block;
  padding: 4px 8px;
  background-color: #e3f2fd;
  color: #1976d2;
  border-radius: 4px;
  font-size: 0.875rem;
  font-weight: 500;
}

.no-category {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 4px 8px;
  background-color: #fff3e0;
  color: #f57c00;
  border-radius: 4px;
  font-size: 0.875rem;
}

.no-category-icon {
  font-style: normal;
  font-size: 0.75rem;
}

/* 开关样式 */
.switch {
  position: relative;
  display: inline-block;
  width: 50px;
  height: 24px;
}

.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  transition: .4s;
  border-radius: 24px;
}

.slider:before {
  position: absolute;
  content: "";
  height: 18px;
  width: 18px;
  left: 3px;
  bottom: 3px;
  background-color: white;
  transition: .4s;
  border-radius: 50%;
}

input:checked + .slider {
  background-color: #2196F3;
}

input:checked + .slider:before {
  transform: translateX(26px);
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.875rem;
  margin-right: 5px;
  transition: all 0.3s ease;
}

.btn-primary {
  background-color: #3498db;
  color: white;
}

.btn-primary:hover {
  background-color: #2980b9;
}

.btn-search {
  background-color: #27ae60;
  color: white;
}

.btn-search:hover {
  background-color: #229954;
}

.btn-edit {
  background-color: #f39c12;
  color: white;
}

.btn-edit:hover {
  background-color: #e67e22;
}

.btn-delete {
  background-color: #e74c3c;
  color: white;
}

.btn-delete:hover {
  background-color: #c0392b;
}

.btn-secondary {
  background-color: #95a5a6;
  color: white;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #ecf0f1;
}

.modal-header h3 {
  margin: 0;
  color: #2c3e50;
}

.close-btn {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: #7f8c8d;
}

.modal-body {
  padding: 20px;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
  color: #2c3e50;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 0.875rem;
}

.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
  outline: none;
  border-color: #3498db;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.form-help {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-top: 5px;
  color: #f57c00;
  font-size: 0.8rem;
}

.help-icon {
  font-style: normal;
  font-size: 0.75rem;
}
</style>